<?php
namespace Admin\Controller;
use Lib\Api\AgentBelongApi;
use Lib\Api\GameTypeApi;
use Lib\Api\OrganizationApi;
use Lib\Api\OrganizationBankApi;
use Lib\Api\OrganizationBelongApi;
use Lib\Api\OrganizationCommissionSetApi;
use Lib\Api\OrganizationRechargeWithdrawalsApi;
use Lib\Api\OrganizationRoleApi;
use Lib\Api\OrganizationSettlementApi;
use Lib\Api\OrganizationStatisticsApi;
use Lib\Api\UserBelongApi;
use Lib\Utils\PayUtils;
use Think\Controller;
class OrganizationController extends Controller {

    public function tree() {
        if (!empty($_POST["s"])) {
            $AGENTCONFIG = C('AGENTCONFIG');
            $level = count($AGENTCONFIG) - session("admin_level");
        } else {
            $level = $_POST['level'];
        }

        $select_org_id = 0;
        if (!empty($_POST['select_org_id'])) {
            $select_org_id = $_POST['select_org_id '];
        }

        $organization_id = session("admin_id");
        if (!empty($_POST['organization_id'])) {
            $organization_id = $_POST['organization_id '];
        }
        $code = session("admin_code");
        $session_level = intval(session("admin_level"));

        $join = 'left join fs_organization b on b.id = a.organization_id left join fs_customer c on c.organization_id = b.id';
        $map['a.belong_organization_id'] = array("eq", $organization_id);
        $map['b.level'] = array("elt", $level);
        $organization_list = OrganizationBelongApi::getAllByCondition($map, $join, "b.*, c.id as customer_id, b.level-1 as p_level, b.level as org_level");

        $node_list = $this->getChildren($organization_list, $code, $session_level, $level, $select_org_id);

        $organization = OrganizationApi::getInfo(array("a.id"=>$organization_id), "a.*, a.level as org_level");
        $isAdd = 0;
        if ($organization['org_level'] == ($level-1)) {
            $isAdd = 1;
        }
        $organization['children'] = $node_list;
        $organization['isAdd'] = $isAdd;
        $organization['open'] = true;
        $organization['isP'] = 0;
        $organization["isSelect"] = 0;

        $this->ajaxReturn($organization);
    }

    public function tree2() {
        $agent_id = $_POST["agent_id"];
        $user_type = $_POST["user_type"];
        $session_level = intval(session("admin_level"));
        if ($session_level < 2) {
            $session_level = 2;
        }
        if ($user_type == 2) {
            $organization = UserBelongApi::getUserBelongOrgByCondition(array("a.user_id"=>$agent_id, "a.state"=>1, "a.organization_level"=>$session_level),"left join fs_organization b on b.id = a.organization_id", "b.*");
            $select_org_id = 0;
            $select_organization = UserBelongApi::getUserBelongOrgByCondition(array("a.user_id"=>$agent_id, "a.state"=>1, "a.organization_level"=>3),"left join fs_organization b on b.id = a.organization_id", "b.id");

        } else {
            $organization = AgentBelongApi::getUserBelongOrgByCondition(array("a.agent_id"=>$agent_id, "a.state"=>1, "a.organization_level"=>$session_level),"left join fs_organization b on b.id = a.organization_id", "b.*");
            $select_org_id = 0;
            $select_organization = AgentBelongApi::getUserBelongOrgByCondition(array("a.agent_id"=>$agent_id, "a.state"=>1, "a.organization_level"=>3),"left join fs_organization b on b.id = a.organization_id", "b.id");
        }

        if (!empty($select_organization)) {
            $select_org_id = $select_organization["id"];
        }
        if (!empty($organization)) {
            $code = $organization["code"];
            $level = $organization["level"];
            $organization_id = $organization["id"];

            $join = 'left join fs_organization b on b.id = a.organization_id left join fs_customer c on c.organization_id = b.id';
            $map['a.belong_organization_id'] = array("eq", $organization_id);
            $map['b.level'] = array("elt", $level+1);
            $organization_list = OrganizationBelongApi::getAllByCondition($map, $join, "b.id, b.name, b.code, b.p_code, b.level as org_level, c.id as customer_id, b.`level`-1 as p_level");

            $node_list = $this->getChildren2($organization_list, $code, $level, ($level+1), $select_org_id);
            $organization['children'] = $node_list;
            $organization['open'] = true;
            $organization['isP'] = 0;
			$organization['selected'] = true;
        }

        $this->ajaxReturn($organization);
    }

    private function getChildren2($data, $code, $index, $level, $select_org_id) {
        if (empty($data)) return [];
        $node_arr = array();
        for ($i = 0; $i<count($data); $i++) {
            if ($data[$i]["p_code"] == $code && $data[$i]["p_level"] == $index) {
                $node = $data[$i];
                $isP = 0;
                if ($node['org_level'] == $level) {
                    $isP = 1;
                } else {
                    $node['children'] = $this->getChildren2($data, $data[$i]["code"], $data[$i]["org_level"], $level, $select_org_id);
                }
                if ($node['id'] == $select_org_id) {
                    $node['selected'] = true;
                }
                $node['open'] = true;
                $node['isP'] = $isP;
                array_push($node_arr, $node);
            }
        }
        return $node_arr;
    }

    private function getChildren($data, $code, $index, $level, $select_org_id) {
        if (empty($data)) return [];
        $node_arr = array();
        for ($i = 0; $i<count($data); $i++) {
            if ($data[$i]["p_code"] == $code && $data[$i]["p_level"] == $index) {
                $node = $data[$i];
                $isSelect = 0;
                $isP = 0;
                $isAdd = 0;
                if ($node['org_level'] == ($level-1)) {
                    $isAdd = 1;
                }
                if ($node['org_level'] == $level) {
                    $isSelect = 1;
                    $isP = 1;
                    $isAdd = 1;
                } else {
                    $node['children'] = $this->getChildren($data, $data[$i]["code"], $data[$i]["org_level"], $level, $select_org_id);
                }
                if ($node['id'] == $select_org_id) {
                    $node['selected'] = true;
                }
                $node['isAdd'] = $isAdd;
                $node['open'] = true;
                $node['isP'] = $isP;
                $node["isSelect"] = $isSelect;
                array_push($node_arr, $node);
            }
        }
        return $node_arr;
    }

    public function addoredit() {
        $modelObj = M("Organization");
        $data = $modelObj->create($_POST);
        if ($_POST['id'] > 0) {
            $where['_string'] = '(name="'.$data['name'].'" OR (code='.$data['code'].' and level='.$data['level'].')) and id not in('.$data['id'].') ';
            $result = OrganizationApi::getTotal($where);
            if ($result == 0) {
                OrganizationApi::save($data);
                $rel['code'] = 1;
                $rel['msg'] = "机构修改成功";
            } else {
                $rel['code'] = -1;
                $rel['msg'] = "机构修改失败，机构编码或机构名称已存在";
            }
        } else {
            $where['_string'] = 'name="'.$data['name'].'" OR (code='.$data['code'].' and level='.$data['level'].') ';
            $result = OrganizationApi::getTotal($where);
            if ($result == 0) {
                $data['balance'] = 0;
                $data['freeze_money'] = 0;
                $data['risk_control_rate'] = 0;
                $data['datetime'] = date("Y-m-d H:i:s");
                $id = OrganizationApi::add($data);
                if ($id > 0) {
                    // 添加机构角色
                    $organizationRole["organization_id"] = $id;
                    $organizationRole["role_id"] = $data['level']+1;
                    OrganizationRoleApi::add($organizationRole);

                    $begin_time = date("Y-m-d H:i:s");
                    $end_time = date("Y-m-d H:i:s",strtotime($begin_time."+1 day"));

                    // 添加机构结算数据
                    $organizationSettlement['organization_id'] = $id;
                    $organizationSettlement['organization_level'] = $data['level'];
                    $organizationSettlement['sys_total_fee'] = 0;
                    $organizationSettlement['total_fee'] = 0;
                    $organizationSettlement['settlement_money'] = 0;
                    $organizationSettlement['cash_profit_loss'] = 0;
                    $organizationSettlement['cash_income'] = 0;
                    $organizationSettlement['state'] = 2;
                    $organizationSettlement['begin_time'] = $begin_time;
                    $organizationSettlement['end_time'] = $end_time;
                    OrganizationSettlementApi::add($organizationSettlement);

                    // 添加机构统计数据
                    $organizationStatistics['organization_id'] = $id;
                    $organizationStatistics['begin_balance'] = 0;
                    $organizationStatistics['recharge'] = 0;
                    $organizationStatistics['recharge_fee'] = 0;
                    $organizationStatistics['withdrawals'] = 0;
                    $organizationStatistics['withdrawals_fee'] = 0;
                    $organizationStatistics['retained_money'] = 0;
                    $organizationStatistics['count_profit'] = 0;
                    $organizationStatistics['fee'] = 0;
                    $organizationStatistics['cash_profit_loss'] = 0;
                    $organizationStatistics['relation_fee'] = 0;
                    $organizationStatistics['original_fee'] = 0;
                    $organizationStatistics['turnover'] = 0;
                    $organizationStatistics['state'] = 2;
                    $organizationStatistics['end_balance'] = 0;
                    $organizationStatistics['begin_time'] = $begin_time;
                    $organizationStatistics['end_time'] = $end_time;
                    OrganizationStatisticsApi::add($organizationStatistics);

                    // 添加机构归属
                    $organization_belong_arr = array();
                    $organization_belong_list = OrganizationBelongApi::getAllList(array("organization_id"=>$_POST['pid']));
                    if (count($organization_belong_list) > 0) {
                        for ($i=0; $i<count($organization_belong_list); $i++) {
                            $organization_belong['organization_id'] = $id;
                            $organization_belong['belong_organization_id'] = $organization_belong_list[$i]['belong_organization_id'];
                            $organization_belong['belong_organization_level'] = $organization_belong_list[$i]['belong_organization_level'];
                            $organization_belong['datetime'] = date('Y-m-d H:i:s');
                            array_push($organization_belong_arr, $organization_belong);
                        }
                    }

                    $organization_belong['organization_id'] = $id;
                    $organization_belong['belong_organization_id'] = $_POST['pid'];
                    $organization_belong['belong_organization_level'] = $_POST['p_level'];
                    $organization_belong['datetime'] = date('Y-m-d H:i:s');
                    array_push($organization_belong_arr, $organization_belong);

                    if (count($organization_belong_arr) > 0) {
                        OrganizationBelongApi::addAll($organization_belong_arr);
                    }

                    // 获取游戏类型
                    $game_list = GameTypeApi::getList(array(), 0, 999999, 'id, show_name, open_time');
                    if (!empty($game_list)) {
                        $organizationCommissionSet_arr = array();
                        for ($i=0; $i<count($game_list); $i++) {
                            // 添加机构默认返佣
                            $userCommissionSet['organization_id'] = $id;
                            $userCommissionSet['game_name'] = $game_list[$i]['show_name'];
                            $userCommissionSet['game_type'] = $game_list[$i]['id'];
                            $userCommissionSet['commission_ratio'] = 0;
                            $userCommissionSet['take_effect_time'] = date('Y-m-d') . ' '. $game_list[$i]['open_time'];
                            $userCommissionSet['datetime'] = date('Y-m-d H:i:s');
                            array_push($organizationCommissionSet_arr, $userCommissionSet);
                        }
                        if (count($organizationCommissionSet_arr) > 0) {
                            OrganizationCommissionSetApi::addAll($organizationCommissionSet_arr);
                        }
                    }
                    $data['id'] = $id;
                    $rel['organization'] = $data;
                    $rel['code'] = 1;
                    $rel['msg'] = "机构添加成功";
                } else {
                    $rel['code'] = -1;
                    $rel['msg'] = "机构添加失败";
                }
            } else {
                $rel['code'] = -1;
                $rel['msg'] = "机构添加失败，机构编码或机构名称已存在";
            }
        }

        $this->ajaxReturn($rel);
    }

    public function setData() {
        $modelObj = M("Organization");
        $data = $modelObj->create($_POST);
        OrganizationApi::save($data);
        $rel['code'] = 1;
        $rel['msg'] = "设置风险控制率成功";
        $this->ajaxReturn($rel);
    }

    // 获取用户返佣设置
    public function getOrganizationCommissionSet() {
        $organization_id = $_POST['organization_id'];
        $game_list = GameTypeApi::getList(array("state" => 1), 1, 99999, "*", "sort asc");
        $organizationCommissionSet_list = OrganizationCommissionSetApi::getAllListByCondition(array("a.organization_id" => $organization_id), "", "a.*", "a.take_effect_time desc");
        $arr = array();
        for ($i=0;$i<count($game_list); $i++) {
            $index = 0;
            $temp_set_list = array();
            for ($j=0;$j<count($organizationCommissionSet_list); $j++) {
                if ($index == 2) break;
                // if (strcasecmp($game_list[$i]['show_name'], $organizationCommissionSet_list[$j]['game_name']) == 0) {
                if (strcasecmp($game_list[$i]['id'], $organizationCommissionSet_list[$j]['game_type']) == 0) {
                    $index++;
                    array_push($temp_set_list, $organizationCommissionSet_list[$j]);
                }
            }
            $organizationCommissionSet['name'] = $game_list[$i]['show_name'];
            $organizationCommissionSet['type'] = $game_list[$i]['id'];
            $organizationCommissionSet['open_time'] = $game_list[$i]['open_time'];
            if (count($temp_set_list) == 2) {
                $c_date = date('Y-m-d H:i:s');
                if(strtotime($c_date) > strtotime($temp_set_list[0]['take_effect_time'])) {
                    $organizationCommissionSet['id'] = 0;
                    $organizationCommissionSet['commission_ratio'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $organizationCommissionSet['is_take_effect'] = 1;
                    $organizationCommissionSet['new_commission_ratio'] = sprintf("%.2f",0);
                    $organizationCommissionSet['take_effect_time'] = '';
                    $organizationCommissionSet['value'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $ajaxdata['last_update_time'] = $temp_set_list[0]['datetime'];
                } else if(strtotime($c_date) > strtotime($temp_set_list[1]['take_effect_time'])) {
                    $organizationCommissionSet['id'] = $temp_set_list[0]['id'];
                    $organizationCommissionSet['commission_ratio'] = sprintf("%.2f",$temp_set_list[1]['commission_ratio']);
                    $organizationCommissionSet['is_take_effect'] = 0;
                    $organizationCommissionSet['new_commission_ratio'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $organizationCommissionSet['take_effect_time'] = $temp_set_list[0]['take_effect_time'];
                    $organizationCommissionSet['value'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                    $ajaxdata['last_update_time'] = $temp_set_list[0]['datetime'];
                }
            } else if (count($temp_set_list) == 1) {
                $organizationCommissionSet['id'] = 0;
                $organizationCommissionSet['commission_ratio'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);
                $organizationCommissionSet['is_take_effect'] = 1;
                $organizationCommissionSet['new_commission_ratio'] = sprintf("%.2f",0);
                $organizationCommissionSet['take_effect_time'] = '';
                $organizationCommissionSet['value'] = sprintf("%.2f",$temp_set_list[0]['commission_ratio']);

                $ajaxdata['last_update_time'] = $temp_set_list[0]['datetime'];

            } else {
                $organizationCommissionSet['id'] = 0;
                $organizationCommissionSet['commission_ratio'] = '--';
                $organizationCommissionSet['is_take_effect'] = 1;
                $organizationCommissionSet['new_commission_ratio'] = sprintf("%.2f",0);
                $organizationCommissionSet['take_effect_time'] = '';
                $organizationCommissionSet['value'] = sprintf("%.2f",0);

                $ajaxdata['last_update_time'] = "--";
            }
            array_push($arr, $organizationCommissionSet);
        }

        $ajaxdata['organizationCommissionSet'] = $arr;

        $this->ajaxReturn($ajaxdata);
    }

    // 设置用户返佣
    public function addOrganizationCommissionSet() {
        $organization_id = $_POST['organization_id'];
        $organizationCommissionSet = $_POST['organizationCommissionSet'];

        if (!empty($organizationCommissionSet)) {
            $add_userCommissionSet_arr = array();
            $isUp = false;
            $sql = "UPDATE fs_organization_commission_set SET datetime=now(), commission_ratio = CASE id ";
            $ids = array();
            for ($i=0; $i<count($organizationCommissionSet); $i++) {
                $value = 0;
                if ($organizationCommissionSet[$i]['value'] > 0) {
                    $value = $organizationCommissionSet[$i]['value'];
                }
                if ($organizationCommissionSet[$i]['id'] == 0) {
                    $obj['organization_id'] = $organization_id;
                    $obj['game_name'] = $organizationCommissionSet[$i]['game_name'];
                    $obj['game_type'] = $organizationCommissionSet[$i]['game_type'];
                    $obj['commission_ratio'] = sprintf("%.2f",$value);
                    $obj['take_effect_time'] = date('Y-m-d',strtotime('+1 day')) . ' '. $organizationCommissionSet[$i]['open_time'];
                    $obj['datetime'] = date('Y-m-d H:i:s');
                    array_push($add_userCommissionSet_arr, $obj);
                } else {
                    $isUp = true;
                    array_push($ids, $organizationCommissionSet[$i]['id']);
                    $sql .= sprintf("WHEN %d THEN %.2f ", $organizationCommissionSet[$i]['id'], $value);
                }
            }

            $sql .= "END WHERE id IN (".implode(',', $ids).")";
            if ($isUp == true) {
                $model = new \Think\Model();
                $model->execute($sql);
            }

            if (count($add_userCommissionSet_arr) > 0) {
                OrganizationCommissionSetApi::addAll($add_userCommissionSet_arr);
            }
            $ajaxdata['code'] = 0;
            $ajaxdata['msg'] = "返佣设置成功，该设置会在下个交易日生效";
        } else {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = "返佣设置失败";
        }
        $this->ajaxReturn($ajaxdata);
    }

    public function organizationBank() {
        $this->display();
    }

    // 获取机构签约列表
    public function toOrganizationBank() {
        $organization_id = session("admin_id");
        $organizationBank_list = OrganizationBankApi::getListAll(array("organization_id"=>$organization_id));

        $organization_list = OrganizationApi::getListAll(array("id"=>$organization_id), "concat(p_code,level,code) as code, name, balance, datetime");

        $rel["organization_bank_list"]=$organizationBank_list;
        $rel["organization_list"]=$organization_list;

        $this->ajaxReturn($rel);
    }

    // 绑定机构签约
    public function bind_bank() {
        $modelObj = M("OrganizationBank");
        $data = $modelObj->create($_POST);

        //数据校验
        if (empty($data['bank_name'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请选择一个签约银行';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($data['province'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请选择一个开户省份';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($data['city'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请选择一个开户城市';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($data['bank_address'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写开户支行';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($data['cardholder'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写开户名称';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($data['bank_no'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写银行账号';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($data['identity'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写身份证号';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($data['mobile_phone'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写手机号码';
            $this->ajaxReturn($ajaxdata);
        }
        // $roles = $_POST['roles'];
        $ajaxdata['code'] = 0;
        if (empty($_POST['id'])) {
            //添加账号是否存在
            $data['organization_id'] = session("admin_id");
            $data["datetime"] = date('Y-m-d H:i:s');
            $id = OrganizationBankApi::add($data);
            $ajaxdata['msg'] = '添加成功';
        } else {
            OrganizationBankApi::save($data);
            $ajaxdata['organizationBank'] = $data;
            $ajaxdata['msg'] = '修改成功';
        }
        $this->ajaxReturn($ajaxdata);
    }

    // 机构小额充值
    public function smallAmountRecharge() {
        if (empty(session('admin_id')) || empty(session('customer_id'))) {
            $ajaxdata['code'] = 0;
            $ajaxdata['msg'] = '充值失败，登录已失效';
            $this->ajaxReturn($ajaxdata);
        }
        $organization_id = session("admin_id");
        $customer_id = session("customer_id");

        $money = 0;
        if (!empty($_POST["money"])) {
            $money = $_POST["money"];
        }
        if ($money <= 0) {
            $ajaxdata['code'] = 0;
            $ajaxdata['msg'] = '充值失败，充值金额错误';
            $this->ajaxReturn($ajaxdata);
            exit;
        }
        $pbank = "";
        if (!empty($_POST["pbank"])) {
            $pbank = $_POST["pbank"];
        }
        if ($pbank == "") {
            $ajaxdata['code'] = 0;
            $ajaxdata['msg'] = '充值失败，请选择支付银行';
            $this->ajaxReturn($ajaxdata);
            exit;
        }
        $type = "";
        if (!empty($_POST["type"])) {
            $type = $_POST["type"];
        }
        $timestamp = date("YmdHis");
        if ($type == "") {
            $ajaxdata['code'] = 0;
            $ajaxdata['msg'] = '充值失败，系统错误';
            $this->ajaxReturn($ajaxdata);
            exit;
        } else if ($type == "zito") {
            $orderNo = "zito_".$organization_id.$customer_id.$timestamp;    //订单号

            $model = M("OrganizationPay");
            $params = array("organization_id"=>$organization_id, "customer_id"=>$customer_id, "order_id"=>$orderNo, "amount"=>"$money", "type"=>$pbank, "status"=>1, "ctime"=>date("Y-m-d H:i:s"));
            $result = $model->add($params);

            if ($result > 0) {
                $result = \Lib\PayApi\Zito\PaymentClient::pay($orderNo, $money, $pbank);
                $result = json_decode($result, true);
                if ($result['success'] == true && $result['code'] == "0x0000") {
                    if (strstr($pbank,"ALIPAY")) {
                        $ajaxdata['code'] = 1;
                        $ajaxdata['src'] = urlencode($result['cashway']);
                        $ajaxdata['url_type'] = "scan";
                        $this->ajaxReturn($ajaxdata);
                    } else {
                        $ajaxdata['code'] = 0;
                        $ajaxdata['msg'] = '充值失败，系统错误';
                        $this->ajaxReturn($ajaxdata);
                    }
                } else {
                    $ajaxdata['code'] = 0;
                    $ajaxdata['msg'] = $result['msg'];
                    $this->ajaxReturn($ajaxdata);
                }
            }
        }

        /*if ($money < 0) {
            exit("充值失败，充值金额错误");
        }

        // $pbank = "KJZF";
        $bankCode = "SPDB";
        $banktongdao = "Yeepay";

        $timestamp = date("YmdHis");
        $pay_memberid = C('__PAYNO2__');   //商户ID
        $Md5key = C('__PAYKEY2__');   //商户ID
        $tjurl = C('__PAYDOMAIN2__');   //提交地址

        $pay_orderid = 'T2'.$organization_id.$pay_memberid.$timestamp;    //订单号
        $pay_amount = $money;    //交易金额
        $pay_applydate = date("Y-m-d H:i:s");  //订单时间
        $pay_bankcode = $bankCode;//"YeePayWx";   //银行编码
        $pay_notifyurl = C("__PAYCALLSERVICE2__");   //异步回掉地址
        $pay_frontendurl = C("__PAYCALLDOMAIN2__");   //服务端返回地址

        $requestarray = array(
            "pay_memberid" => $pay_memberid,
            "pay_orderid" => $pay_orderid,
            "pay_amount" => $pay_amount,
            "pay_applydate" => $pay_applydate,
            "pay_bankcode" => $pay_bankcode,
            "pay_notifyurl" => $pay_notifyurl,
            "pay_callbackurl" => $pay_frontendurl
        );
        $model = M("OrganizationPay");
        $params = array("organization_id"=>$organization_id, "customer_id"=>$customer_id, "order_id"=>$pay_orderid, "amount"=>"$money", "type"=>$banktongdao, "status"=>1, "ctime"=>date("Y-m-d H:i:s"));
        $result = $model->add($params);
        if ($result > 0) {
            ksort($requestarray);
            reset($requestarray);

            $md5str = "";
            foreach ($requestarray as $key => $val) {
                $md5str = $md5str . $key . "=>" . $val . "&";
            }
            $sign = strtoupper(md5($md5str . "key=" . $Md5key));
            $requestarray["pay_md5sign"] = $sign;
            $requestarray["tongdao"] = $banktongdao;
            // $requestarray["pay_reserved1"] = $bankCode;

            $str = '<form id="Form1" name="Form1" method="post" action="' . $tjurl . '">';
            foreach ($requestarray as $key => $val) {
                $str = $str . '<input type="hidden" name="' . $key . '" value="' . $val . '">';
            }
            // $str = $str . '<input type="submit" value="提交">';
            $str = $str . '</form>';
            $str = $str . '<script>';
            $str = $str . 'document.Form1.submit();';
            $str = $str . '</script>';
            $str = $str . '正在跳转充值页面...';
            exit($str);
        }*/
        // exit("OK");
    }

    public function q_scan($codeUrl) {
        qrcode(urldecode($codeUrl), 6);
    }

    // 机构充值
    public function recharge() {
        $organization_id = session("admin_id");
        $customer_id = session("customer_id");

        $model = M("OrganizationBank");
        $organizationBank = $model->create($_POST);
        $organizationBankTotal = OrganizationBankApi::getTotal(array("organization_id"=>$organization_id));

        // 判断是否绑定过银行
        if ($organizationBankTotal == 0) {

            //数据校验
            if (empty($organizationBank['bank_name'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请选择一个签约银行';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($organizationBank['province'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请选择一个开户省份';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($organizationBank['city'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请选择一个开户城市';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($organizationBank['bank_address'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请填写开户支行';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($organizationBank['cardholder'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请填写开户名称';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($organizationBank['bank_no'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请填写银行账号';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($organizationBank['identity'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请填写身份证号';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($organizationBank['mobile_phone'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请填写手机号码';
                $this->ajaxReturn($ajaxdata);
            }
            if (empty($_POST['money'])) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请填写入金金额';
                $this->ajaxReturn($ajaxdata);
            }
            if (floatval($_POST['money']) < 0) {
                $ajaxdata['code'] = -1;
                $ajaxdata['msg'] = '请填写正确的入金金额';
                $this->ajaxReturn($ajaxdata);
            }

            $organizationBank['organization_id'] = $organization_id;
            $organizationBank["datetime"] = date('Y-m-d H:i:s');
            OrganizationBankApi::add($organizationBank);
        }

        // 添加入金申请
        $out_trade_no = "JG".date('YmdHi').$organization_id.rand_number(1, 999);
        $organizationRechargeWithdrawals["organization_id"] = $organization_id;
        $organizationRechargeWithdrawals["customer_id"] = $customer_id;
        $organizationRechargeWithdrawals["out_trade_no"] = $out_trade_no;
        $organizationRechargeWithdrawals["money"] = $_POST['money'];
        $organizationRechargeWithdrawals["fee"] = 0;
        $organizationRechargeWithdrawals["type"] = 1;
        $organizationRechargeWithdrawals["state"] = 0;
        $organizationRechargeWithdrawals["bank_name"] = $organizationBank['bank_name'];
        $organizationRechargeWithdrawals["bank_no"] = $organizationBank['bank_no'];
        $organizationRechargeWithdrawals["cardholder"] = $organizationBank['cardholder'];
        $organizationRechargeWithdrawals["identity"] = $organizationBank['identity'];
        $organizationRechargeWithdrawals["mobile_phone"] = $organizationBank['mobile_phone'];
        $organizationRechargeWithdrawals["datetime"] = date('Y-m-d H:i:s');
        $organizationRechargeWithdrawals["audit_state"] = 2;
        OrganizationRechargeWithdrawalsApi::add($organizationRechargeWithdrawals);

        $ajaxdata['code'] = 0;
        $ajaxdata['msg'] = '入金申请已提交';
        $this->ajaxReturn($ajaxdata);
    }


    public function withdrawals() {
        $model = M("OrganizationBank");
        $organizationBank = $model->create($_POST);
        //数据校验
        if (empty($organizationBank['bank_name'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请选择一个签约银行';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($organizationBank['province'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请选择一个开户省份';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($organizationBank['city'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请选择一个开户城市';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($organizationBank['bank_address'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写开户支行';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($organizationBank['cardholder'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写开户名称';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($organizationBank['bank_no'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写银行账号';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($organizationBank['identity'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写身份证号';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($organizationBank['mobile_phone'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写手机号码';
            $this->ajaxReturn($ajaxdata);
        }
        if (empty($_POST['money'])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写入金金额';
            $this->ajaxReturn($ajaxdata);
        }
        if (floatval($_POST['money']) < 0) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '请填写正确的入金金额';
            $this->ajaxReturn($ajaxdata);
        }
        $money = floatval($_POST['money']);

        $organization_id = session("admin_id");
        $customer_id = session("customer_id");
        // 判断是否绑定过银行
        $organizationBankTotal = OrganizationBankApi::getTotal(array("organization_id"=>$organization_id));
        if ($organizationBankTotal == 0) {
            $organizationBank['organization_id'] = $organization_id;
            $organizationBank["datetime"] = date('Y-m-d H:i:s');
            OrganizationBankApi::add($organizationBank);
        }

        $organization = OrganizationApi::getInfoByCondition(array("id"=>$organization_id), "", "id, balance, freeze_money");
        if ($money > floatval($organization["balance"])) {
            $ajaxdata['code'] = -1;
            $ajaxdata['msg'] = '机构资金不足';
            $this->ajaxReturn($ajaxdata);
        }

        $organization["balance"] = array('exp','balance-'.$money);
        $organization["freeze_money"] = array('exp','freeze_money+'.$money);
        OrganizationApi::save($organization);

        // 添加入金申请
        $out_trade_no = "JG".date('YmdHi').$organization_id.rand_number(1, 999);
        $organizationRechargeWithdrawals["organization_id"] = $organization_id;
        $organizationRechargeWithdrawals["customer_id"] = $customer_id;
        $organizationRechargeWithdrawals["out_trade_no"] = $out_trade_no;
        $organizationRechargeWithdrawals["money"] = $money;
        $organizationRechargeWithdrawals["fee"] = 0;
        $organizationRechargeWithdrawals["type"] = 2;
        $organizationRechargeWithdrawals["state"] = 0;
        $organizationRechargeWithdrawals["bank_name"] = $organizationBank['bank_name'];
        $organizationRechargeWithdrawals["bank_no"] = $organizationBank['bank_no'];
        $organizationRechargeWithdrawals["cardholder"] = $organizationBank['cardholder'];
        $organizationRechargeWithdrawals["identity"] = $organizationBank['identity'];
        $organizationRechargeWithdrawals["mobile_phone"] = $organizationBank['mobile_phone'];
        $organizationRechargeWithdrawals["datetime"] = date('Y-m-d H:i:s');
        $organizationRechargeWithdrawals["audit_state"] = 2;
        OrganizationRechargeWithdrawalsApi::add($organizationRechargeWithdrawals);

        $ajaxdata['code'] = 0;
        $ajaxdata['msg'] = '出金申请已提交';
        $this->ajaxReturn($ajaxdata);
    }

    public function rechargeOrWithdrawals() {
        $this->display();
    }

    public function toRechargeOrWithdrawals() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $organization_level = session("admin_level");

        $where = array();
        if ($organization_level > 0) {
            $organization_id = session("admin_id");
            $where['a.organization_id'] = $organization_id;
        }
        $left = "left join fs_organization b on b.id = a.organization_id";
        $left .=" left join fs_customer c on c.id = a.customer_id";
        $left .=" left join fs_customer d on d.id = a.audit_org";
        $field = "a.*, b.name as organization_name, b.balance as organization_balance, c.real_name as customer_name, ifnull(d.real_name, '--') as audit_org, ifnull(a.audit_date, '--') as audit_date";
        $list = OrganizationRechargeWithdrawalsApi::getList($where, $left, $page_num, $page_size, $field, "a.datetime desc");
        $total = OrganizationRechargeWithdrawalsApi::getTotal($where);
        $data = pageHelper($page_size, $page_num, $list, $total);
        $rel['data'] = $data;
        $this->ajaxReturn($rel);
    }

    public function auditRechargeOrWithdrawals() {
        $this->display();
    }

    public function toAuditRechargeOrWithdrawals() {
        $page_size = $_POST['page_size'];
        $page_num = $_POST['page_num'];
        $organization_id = session("admin_id");

        $left = "left join fs_organization_belong e on e.organization_id = a.organization_id";
        $left .= " left join fs_organization b on b.id = a.organization_id";
        $left .=" left join fs_customer c on c.id = a.customer_id";
        $left .=" left join fs_customer d on d.id = a.audit_org";
        $field = "a.*, b.name as organization_name, b.balance as organization_balance, c.real_name as customer_name, ifnull(d.real_name, '--') as audit_org, ifnull(a.audit_date, '--') as audit_date";
        $map["e.belong_organization_id"] = $organization_id;
        $map["a.audit_state"] = 2;
        $map['DATE_FORMAT(e.datetime, "%Y-%m-%d %H:%i:%s")'] = array('elt', 'DATE_FORMAT("'.date('Y-m-d H:i:s').'", "%Y-%m-%d %H:%i:%s")');
        $list = OrganizationRechargeWithdrawalsApi::getList($map, $left, $page_num, $page_size, $field, "a.datetime desc");
        $total = OrganizationRechargeWithdrawalsApi::getTotal($map, $left);
        $data = pageHelper($page_size, $page_num, $list, $total);
        $rel['data'] = $data;
        $this->ajaxReturn($rel);
    }


    public function subAuditRechargeOrWithdrawals() {
        $organization_id = session("admin_id");
        $id = $_POST["id"];
        $audit_state = $_POST["audit_state"];
        $auto = $_POST['auto'];
        $organizationRechargeWithdrawals = OrganizationRechargeWithdrawalsApi::getInfo(array("id"=>$id, "audit_state"=>2));
        if (!empty($organizationRechargeWithdrawals)) {
            $organization = OrganizationApi::getInfoByCondition(array('a.id'=>$organizationRechargeWithdrawals["organization_id"]), "", 'a.id, a.balance, a.freeze_money');
            $money = floatval($organizationRechargeWithdrawals["money"]);
            $fee = floatval($organizationRechargeWithdrawals["fee"]);
            $rel = false;
            if ($organizationRechargeWithdrawals["type"] == 1) {
                if ($audit_state == 1) {
					$fee = 0;
                    $balance = $money-$fee;
                    $organization['balance'] = array('exp','balance+'.$balance);
                    $rel = OrganizationApi::save($organization);

                    $organizationStatistics = OrganizationStatisticsApi::getInfo(array("organization_id"=>$organizationRechargeWithdrawals["organization_id"], "state"=>2));
                    $organizationStatistics["recharge"] = array('exp','recharge+'.$balance);
                    $organizationStatistics["recharge_fee"] = array('exp','recharge_fee+'.$fee);
                    OrganizationStatisticsApi::save($organizationStatistics);
                } else if ($audit_state == 3) {
                    $rel = true;
                }
            } else {
                if ($audit_state == 1) {
                    $model = M("Sys");
                    $data = $model->field("withdrawals_fee")->where(array('id' => 1))->find();
                    $fee = $money * (floatval($data['withdrawals_fee'])/100);
                    $withdrawals_money = $money-$fee;
                    $flag = true;
                    if ($auto == 1) {
                        $flag = false;
                        if (!empty($organizationRechargeWithdrawals['bank_name']) && !empty($organizationRechargeWithdrawals['bank_no']) && !empty($organizationRechargeWithdrawals['cardholder']) && !empty($organizationRechargeWithdrawals['identity']) && !empty($organizationRechargeWithdrawals['mobile_phone'])) {
                            $timestamp = date("YmdHis");
                            $pay_memberid = C('__PAYNO__');             //商户ID
                            $pay_notifyurl = C("__PAYCALLSERVICE__");   //异步回掉地址
                            $tranId = $organizationRechargeWithdrawals['out_trade_no'];    //订单号
                            $amount = $withdrawals_money*100;
                            if ($amount > 0) {
                                $str = '<?xml version="1.0" encoding="utf-8" standalone="no"?><message application="ReceivePay" merchantId="'.$pay_memberid.'" tranId="'.$tranId.'" timestamp="'.$timestamp.'" receivePayNotifyUrl="'.$pay_notifyurl.'" accountProp="0" receivePayType="1" bankGeneralName="'.$organizationRechargeWithdrawals['bank_name'].'" accNo="'.$organizationRechargeWithdrawals['bank_no'].'" accName="'.$organizationRechargeWithdrawals['cardholder'].'" amount="'.$amount.'" credentialType="01" credentialNo="'.$organizationRechargeWithdrawals['identity'].'" tel="'.$organizationRechargeWithdrawals['mobile_phone'].'" version="1.0.1" />';
                                $msg_str = PayUtils::getStrMsg($str);

                                $gateway_url = C('__PAYDOMAIN__');   //提交地址
                                $ch = curl_init();
                                curl_setopt($ch, CURLOPT_URL, $gateway_url);
                                curl_setopt($ch, CURLOPT_POST, true);
                                curl_setopt($ch, CURLOPT_POSTFIELDS, $msg_str);
                                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                $result = curl_exec($ch);
                                $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                                curl_close($ch);
                                /******异步通知，请参考下面过程******/
                                $tmp = explode("|", $result);
                                $resp_xml = base64_decode($tmp[0]);
                                $resp_sign = $tmp[1];
                                if(PayUtils::verity(md5($resp_xml,true),$resp_sign)) { //验签
                                    $postObj = simplexml_load_string($resp_xml);
                                    if ($postObj['respCode'] == '000') {
                                        $fp = fopen('org_aaaa.txt','w+');
                                        fwrite($fp,$resp_xml);
                                        fclose($fp);
                                        // $rel_data['msg'] = $postObj['respDesc'];
                                        // $rel_data['code'] = -1;
                                        $flag = true;
                                    }
                                }
                            }
                        } else {
                            $flag = false;
                        }
                    }

                    if ($flag == true) {
                        $organization['freeze_money'] = array('exp','freeze_money-'.$money);
                        $rel = OrganizationApi::save($organization);

                        $organizationStatistics = OrganizationStatisticsApi::getInfo(array("organization_id"=>$organizationRechargeWithdrawals["organization_id"], "state"=>2));
                        $organizationStatistics["withdrawals"] = array('exp','withdrawals+'.$money);
                        $organizationStatistics["withdrawals_fee"] = array('exp','withdrawals_fee+'.$fee);
                        OrganizationStatisticsApi::save($organizationStatistics);
                    }
                } else if ($audit_state == 3) {
                    $organization['balance'] = array('exp','balance+'.$money);
                    $organization['freeze_money'] = array('exp','freeze_money-'.$money);
                    $rel = OrganizationApi::save($organization);
                }

            }

            if ($rel) {
                $organization = OrganizationApi::getInfoByCondition(array('a.id'=>$organizationRechargeWithdrawals["organization_id"]), "", 'a.id, a.balance');
                $params = array("organization_id"=>$organization["id"], "money"=>$money, "fee"=>$fee, "balance"=>$organization["balance"],
                    "type"=>$organizationRechargeWithdrawals["type"], "out_trade_no"=>$organizationRechargeWithdrawals["out_trade_no"], "datetime"=>date('Y-m-d H:i:s'));
                $modelObj = M("OrganizationTradeDetail");
                $modelObj->add($params);

                $state = 1;
                if ($audit_state == 3) {
                    $state = 2;
                }
                $organizationRechargeWithdrawals["state"] = $state;
                $organizationRechargeWithdrawals["audit_state"] = $audit_state;
                $organizationRechargeWithdrawals["audit_org"] = $organization_id;
                $organizationRechargeWithdrawals["audit_date"] = date('Y-m-d H:i:s');

                OrganizationRechargeWithdrawalsApi::save($organizationRechargeWithdrawals);
            }
        }
    }

    public function zito_notify() {
        $result = file_get_contents("php://input");
        $result = json_decode($result, true);

        if ($result['success'] == true) {
            $model = M("OrganizationPay");
            $payMap['order_id'] = array("eq", $result['orderidinf']);
            $payMap['status'] = 1;
            $payObj = $model->where($payMap)->find(); // 根据条件查找

            if (!empty($payObj)) {
                $query_result = \Lib\PayApi\Zito\PaymentClient::query($result['orderId']);
                $query_result = json_decode($query_result, true);
                if ($query_result['success'] == true && $query_result['code'] == "0x0000") {
                    $order = $query_result['orderList'][0];
                    if ($order['state'] == 1) {
                        $payObj['status'] = 2;
                        $model->save($payObj);

                        $zito = C('ZITO');
                        $bank = "";
                        foreach ($zito['tongdao'] as $key => $val) {
                            foreach ($val as $key2 => $val2) {
                                if ($val2 == $order['getewayid']) {
                                    $bank = $key;
                                    break;
                                }
                            }
                        }
                        $remark = "融智付";
                        if ($bank == "ALIPAY") {
                            $remark = "支付宝充值";
                        }

                        $organization_id = $payObj['organization_id'];
                        $customer_id = $payObj['customer_id'];
                        $money = floatval($payObj['amount']);
                        $out_trade_no = $payObj['order_id'];
                        $this->updateOrganizationMoney($money, $out_trade_no, $organization_id, $customer_id, $remark);
                        $payObj['status'] = 3;
                        $model->save($payObj);
                    }
                }
            } else {
                $fp = fopen('zito_chongzhi_rel.txt','w+');
                fwrite($fp, "没有找到订单：".$result['orderidinf']);
                fclose($fp);
            }
        }
    }

    private function updateOrganizationMoney($money, $out_trade_no, $organization_id, $customer_id, $remark) {
        $modelName = 'Sys';
        $model = M($modelName);
        $data = $model->field("recharge_fee")->where(array('id' => 1))->find();
        $rechargeMoney = floatval($money);
        $fee = $rechargeMoney * (floatval($data['recharge_fee'])/100);

        $money = $rechargeMoney-$fee;

        $model = M("OrganizationTradeDetail");
        $tradeDetailMap["out_trade_no"] = $out_trade_no;
        $tradeDetailMap["type"] = 1;
        $tradeDetail_data = $model->where($tradeDetailMap)->count("id");

        if ($tradeDetail_data == 0) {
            $model = M("Organization");
            $data["id"] = $organization_id;
            $data['balance'] = array('exp','balance+'.$money);
            $model->save($data);

            // Events::eventsHandle($user_id, $money);
            $organizationRechargeWithdrawals["organization_id"] = $organization_id;
            $organizationRechargeWithdrawals["customer_id"] = $customer_id;
            $organizationRechargeWithdrawals["out_trade_no"] = $out_trade_no;
            $organizationRechargeWithdrawals["money"] = $money;
            $organizationRechargeWithdrawals["fee"] = $fee;
            $organizationRechargeWithdrawals["type"] = 1;
            $organizationRechargeWithdrawals["state"] = 1;
            $organizationRechargeWithdrawals["bank_name"] = $remark;
            $organizationRechargeWithdrawals["bank_no"] = "";
            $organizationRechargeWithdrawals["cardholder"] = "";
            $organizationRechargeWithdrawals["datetime"] = date('Y-m-d H:i:s');
            $organizationRechargeWithdrawals["audit_state"] = 1;
            $organizationRechargeWithdrawals["audit_date"] = date('Y-m-d H:i:s');
            OrganizationRechargeWithdrawalsApi::add($organizationRechargeWithdrawals);

            $organization = OrganizationApi::getInfoByCondition(array('a.id'=>$organization_id), "", 'a.id, a.balance');
            $params = array("organization_id"=>$organization["id"], "money"=>$money, "fee"=>$fee, "balance"=>$organization["balance"],
                "type"=>1, "out_trade_no"=>$out_trade_no, "datetime"=>date('Y-m-d H:i:s'));
            $modelObj = M("OrganizationTradeDetail");
            $modelObj->add($params);

            $organizationStatistics = OrganizationStatisticsApi::getInfo(array("organization_id"=>$organization_id, "state"=>2));
            $organizationStatistics["recharge"] = array('exp','recharge+'.$money);
            $organizationStatistics["recharge_fee"] = array('exp','recharge_fee+'.$money);
            OrganizationStatisticsApi::save($organizationStatistics);

        }
    }
}